/**
 * API 工具函数
 * 统一管理前端API请求
 */

import { API_CONFIG } from '../config'

// 创建基础请求函数
const createRequest = () => {
  const baseURL = API_CONFIG.baseURL
  const timeout = API_CONFIG.timeout

  return {
    async request(url, options = {}) {
      const fullUrl = `${baseURL}${url}`
      const defaultOptions = {
        timeout,
        headers: {
          'Content-Type': 'application/json',
          ...options.headers
        }
      }

      try {
        const response = await fetch(fullUrl, { ...defaultOptions, ...options })
        const data = await response.json()
        
        if (!response.ok) {
          throw new Error(data.message || 'Request failed')
        }
        
        return data
      } catch (error) {
        console.error('API Request Error:', error)
        throw error
      }
    },

    get(url, options = {}) {
      return this.request(url, { ...options, method: 'GET' })
    },

    post(url, data, options = {}) {
      return this.request(url, {
        ...options,
        method: 'POST',
        body: JSON.stringify(data)
      })
    },

    put(url, data, options = {}) {
      return this.request(url, {
        ...options,
        method: 'PUT',
        body: JSON.stringify(data)
      })
    },

    delete(url, options = {}) {
      return this.request(url, { ...options, method: 'DELETE' })
    }
  }
}

// 导出API实例
export const api = createRequest()

// 具体API方法
export const authAPI = {
  login: (credentials) => api.post('/api/login', credentials),
  register: (userData) => api.post('/api/register', userData)
}

export const userAPI = {
  getUsers: () => api.get('/api/users'),
  getUser: (id) => api.get(`/api/user/${id}`)
}

export const projectAPI = {
  getProjects: () => api.get('/api/projects'),
  createProject: (projectData) => api.post('/api/project', projectData)
}

export const healthAPI = {
  check: () => api.get('/api/health')
}

export default api